import React, { useState, useEffect, useCallback } from 'react';
import {
  homeIndustryStatistic,
  homeTargetStatistic,
  homeOutboundStatistic,
} from 'admin/servers/servers';
import OneOfThree from './OneOfThree';
import OneOfTwo from './OneOfTwo';
import OneOfOne from './OneOfOne';
import type { IAuth } from '../constant';

interface Props {
  smsAuth: IAuth;
  authCount: number;
}

const onlyOneAuthMap = {
  data: {
    title: '行业短信',
    unit: '（条）',
    fetchApi: homeIndustryStatistic,
    path: '/webapp/casStatistics/industrySms',
  },
  target: {
    title: '靶向短信',
    unit: '（条）',
    fetchApi: homeTargetStatistic,
    path: '/webapp/casStatistics/targetedSms',
  },
  call: {
    title: '智能外呼',
    unit: '（分钟）',
    fetchApi: homeOutboundStatistic,
    path: '/webapp/casStatistics/intelligentCall',
  },
};

const TopStatistic: React.FC<Props> = ({ smsAuth, authCount }) => {
  const [onlyOne, setOnlyOne] = useState<string>(''); // 如只有一个

  const extractUniqueness = useCallback(() => {
    // 只有1个
    if (authCount === 1) {
      const [[key]] = Object.entries(smsAuth).filter(([key, value]) => {
        return value === 2;
      });
      setOnlyOne(key);
    }
  }, [authCount, smsAuth]);

  useEffect(() => {
    extractUniqueness();
  }, [extractUniqueness]);

  return (
    <div className="row-wrapper">
      {authCount === 3 && (
        <>
          <OneOfThree
            title="行业短信息发送量（条）"
            fetchApi={homeIndustryStatistic}
            path="/webapp/casStatistics/industrySms"
          />
          <OneOfThree
            title="靶向短信总发送量（条）"
            fetchApi={homeTargetStatistic}
            path="/webapp/casStatistics/targetedSms"
          />
          <OneOfThree
            title="智能外呼（分钟）"
            fetchApi={homeOutboundStatistic}
            path="/webapp/casStatistics/intelligentCall"
          />
        </>
      )}
      {authCount === 2 && (
        <>
          {smsAuth.data === 2 && (
            <OneOfTwo
              title="行业短信息发送量（条）"
              fetchApi={homeIndustryStatistic}
              path="/webapp/casStatistics/industrySms"
            />
          )}
          {smsAuth.target === 2 && (
            <OneOfTwo
              title="靶向短信总发送量（条）"
              fetchApi={homeTargetStatistic}
              path="/webapp/casStatistics/targetedSms"
            />
          )}
          {smsAuth.call === 2 && (
            <OneOfTwo
              title="智能外呼（分钟）"
              fetchApi={homeOutboundStatistic}
              path="/webapp/casStatistics/intelligentCall"
            />
          )}
        </>
      )}
      {authCount === 1 && <OneOfOne onlyOne={onlyOneAuthMap[onlyOne]} />}
    </div>
  );
};

export default TopStatistic;
